package cn.yr.clock.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.yr.clock.domain.entity.Engine;
import cn.yr.clock.domain.entity.Record;
import cn.yr.clock.domain.entity.User;
import cn.yr.clock.domain.vo.PageVo;
import cn.yr.clock.domain.vo.RecordVo;
import cn.yr.clock.handler.CacheUserHandler;
import cn.yr.clock.handler.EngineHandler;
import cn.yr.clock.service.RecordService;
import cn.yr.common.exception.ret.Ret;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;


/**
 * @author Lang
 * @email 1102076808@qq.com
 * @date 2021-09-25 11:13:41
 */
@RestController
@RequestMapping("/record")
public class RecordController {
    @Autowired
    private RecordService recordService;

    @Autowired
    private CacheUserHandler cacheUserHandler;

    @Autowired
    private EngineHandler engineHandler;

    @RequestMapping("/hasRecordToday")
    public Ret<Boolean> hasRecordToday() {
        Long userId = cacheUserHandler.getUser().getUserId();
        Boolean aBoolean = recordService.hasRecordToday(userId,new Date());
        return Ret.success(aBoolean);
    }

    /**
     * 列表
     */
    @RequestMapping("/page")
    public Ret<PageVo<Record>> page(@RequestBody PageVo<Record> pageVo) {
        Long userId = cacheUserHandler.getUser().getUserId();
        QueryWrapper<Record> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId);
        PageVo<Record> pageRecord = recordService.page(pageVo, wrapper);
        return Ret.success(pageRecord);
    }

    /**
     * 列表
     */
    @RequestMapping("/list")
    public Ret<List<RecordVo>> list() {
        Long userId = cacheUserHandler.getUser().getUserId();
        QueryWrapper<Record> wrapper = new QueryWrapper<>();
        wrapper.eq("clock_user", userId);
        List<Record> list = recordService.list(wrapper);
        List<RecordVo> collect = list.stream().map(item -> {
            RecordVo recordVo = new RecordVo();
            BeanUtil.copyProperties(item, recordVo);
            recordVo.setClockTimeStr(DateUtil.format(item.getClockTime(), "yyyy-MM-dd"));
            return recordVo;
        }).collect(Collectors.toList());
        return Ret.success(collect);
    }

    /**
     * 列表
     */
    @RequestMapping("/listTime")
    public Ret<List<String>> listTime() {
        Long userId = cacheUserHandler.getUser().getUserId();
        QueryWrapper<Record> wrapper = new QueryWrapper<>();
        wrapper.eq("clock_user", userId);
        recordService.getMap(wrapper);
        List<Record> list = recordService.list(wrapper);
        List<String> strings = list.stream().map(record -> DateUtil.format(record.getClockTime(), "yyyy-MM-dd"))
                .collect(Collectors.toList());
        return Ret.success(strings);
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{recordId}")
    public Ret<Record> info(@PathVariable("recordId") Long recordId) {
        Record record = recordService.getById(recordId);
        return Ret.success(record);
    }

    @RequestMapping("/test")
    public Ret<Object> test() {
        DateTime date = DateUtil.offsetDay(new Date(), -20);
        for (int i = 0; i < 20; i++) {
            DateTime dateTime = DateUtil.offsetDay(date, 1);
            date = DateUtil.offsetDay(date, 1);
            Record record = new Record();
            record.setClockTime(dateTime);
            record.setNote(i + "");
            Long userId = 1L;
            recordService.clock(record, userId, new Date());
        }
        return Ret.success();
    }

    /**
     * 打卡核心
     */
    @RequestMapping("/add")
    public Ret<Object> save(@Validated @RequestBody Record record) {
        if (ObjectUtil.isNull(record)) {
            return Ret.error("请提交打卡信息");
        }
        if (StrUtil.isBlank(record.getImg())) {
            return Ret.error("请上传有效打卡截图");
        }
        if (StrUtil.isBlank(record.getNote())) {
            return Ret.error("请输入打卡内容");
        }
        Long userId = cacheUserHandler.getUser().getUserId();
        return recordService.clock(record, userId, new Date());
    }


    @RequestMapping("supplementClock")
    public Ret<Object> supplementClock(@Validated @RequestBody Record record) {
        if (ObjectUtil.isNull(record)) {
            return Ret.error("请提交补卡信息");
        }
        if (StrUtil.isBlank(record.getImg())) {
            return Ret.error("请上传有效补卡截图");
        }
        if (StrUtil.isBlank(record.getNote())) {
            return Ret.error("请输入补卡内容");
        }
        if (ObjectUtil.isNull(record.getClockTime())) {
            return Ret.error("请输入补卡时间");
        }
        Long userId = cacheUserHandler.getUser().getUserId();
        return recordService.supplementClock(record, userId, record.getClockTime());
    }

    /**
     * 修改
     */
    @RequestMapping("/edit")
    public Ret<Object> update(@Validated @RequestBody Record record) {
        recordService.updateById(record);
        return Ret.success();
    }

    /**
     * 删除
     */
    @RequestMapping("/remove")
    public Ret<Object> delete(@RequestBody Long[] recordIds) {
        recordService.removeByIds(Arrays.asList(recordIds));
        return Ret.success();
    }

    /**
     * 首页随机提示
     * @return
     */
    @RequestMapping("/listNotice")
    public Ret<List<String>> listNotice() {
        User user = cacheUserHandler.getUser();
        ArrayList<String> list = new ArrayList<>();
        int i = RandomUtil.randomInt(1, 3);
        if (ObjectUtil.isNull(user) || i == 1) {
            list.add("知足且上进");
            list.add("温柔又坚定");
        } else if (i == 2) {
            Long userId = user.getUserId();
            QueryWrapper<Record> wrapper = new QueryWrapper<>();
            wrapper.eq("clock_user", userId);
            wrapper.orderByDesc("clock_time");
            Record record = recordService.getOne(wrapper, false);
            if (ObjectUtil.isNull(record)) {
                list.add("快开始你的第一次打卡吧");
            } else {
                Integer sumClock = engineHandler.sumClock(userId);
                Integer continuousClock = engineHandler.continuousClock(userId);
                list.add("嗨呀  您已经");
                list.add("累计打卡了" + sumClock + "天");
                list.add("连续打卡了" + continuousClock + "天");
                list.add("请继续加油呀!!!");
            }
        }
        return Ret.success(list);

    }

}
